<template>
    <div class="customcond-content">
        <div>
            <div v-show="labqueryflag" style="height:90px">
                <div class="param-row">
                    <span class="param-title">条件代码</span>
                    <span class="param-text">
                        <el-input v-model="labqueryParam.queryresultno" style="width:100%" ref="input1" @keyup.enter.native="nextFocus(1)"></el-input>
                    </span>
                    <span class="param-title">条件名称</span>
                    <span class="param-text">
                        <el-input v-model="labqueryParam.queryresultname" style="width:100%" ref="input2" @keyup.enter.native="nextFocus(2)"></el-input>
                    </span>
                    <span class="param-title">用户</span>
                    <span class="param-text">
                        <rm-ddl-common datatype="userinfo" dataname="用户" v-model="labqueryParam.createuser" width="100%" :disabled="utype!='G'"></rm-ddl-common>
                    </span>
                </div>
                <div class="param-row" style="margin-top: 5px;">
                    <span class="param-title">备注</span>
                    <span style="width: 700px;">
                        <el-input type="textarea" v-model="labqueryParam.description" rows="2" ref="input3" @keyup.enter.native="nextFocus(3)"></el-input>
                    </span>
                </div>
            </div>
            <div class="customcond-operate">
                <div>
                    <span v-if="condtype == 2" class="medcond-tip">药敏结果输入方式 例：敏感，耐药，空 （空代表该抗生素无药敏结果）</span>
                </div>
                <div>
                    <el-button icon="el-icon-save" style="align:right" @click="btnSure" v-show="!labqueryflag" type="primary">确定</el-button>
                    <el-button icon="el-icon-save" style="align:right" @click="btnCancel" v-show="!labqueryflag">取消</el-button>
                    <el-button icon="el-icon-plus" style="align:left" @click="addItem">新增明细</el-button>
                    <el-button icon="el-icon-delete" style="align:left" @click="delItem">删除明细</el-button>
                    <el-button icon="el-icon-save" style="align:right" @click="btnToSave" v-show="!labqueryflag&&addPowerflag">另存为</el-button>
                    <el-button icon="el-icon-save" style="align:right" @click="saveLabquery" v-show="labqueryflag" type="primary">保存</el-button>
                    <el-button icon="el-icon-save" style="align:right" @click="btnGoBack" v-show="labqueryflag">返回</el-button>
                </div>
            </div>
            <div v-if="condtype == 1" style="height:270px">
                <vxe-table ref="resultTable" show-overflow :data.sync="condList" height="auto" resizable stripe border size="mini" 
                    header-align="center" show-header-overflow highlight-current-row @cell-dblclick="cellDblclick" 
                    :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, showIcon: false }">
                    <vxe-table-column field="seq" title="序号" align="center" width="55" :edit-render="{name: 'input'}" sortable></vxe-table-column>
                    <vxe-table-column field="rpt_itemname" title="报告项目(双击弹窗)" width="145" :edit-render="{name:'input', autoselect: true, attrs: {readonly: true}}" sortable></vxe-table-column>
                    <vxe-table-column field="resistrules" title="耐药机制" width="150" :edit-render="{type: 'default'}">
                        <template v-slot="{ row }">
                            <el-select v-model="row.resistrules"  @dblclick.native="popMultipleChk(row.resistrules, 'resistrules', rescodeOption, '耐药机制选择')" style="width: 100%;" filterable clearable>
                                <el-option v-for="(item, index) in rescodeOption" :key="index" :value="item.data" :label="item.display"> </el-option>
                            </el-select>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="lowlimit" title="数值结果<" width="90" :edit-render="{name: 'input',autoselect: true}" sortable></vxe-table-column>
                    <vxe-table-column field="uplimit" title="数值结果>" width="90" :edit-render="{name: 'input',autoselect: true,}" sortable></vxe-table-column>
                    <vxe-table-column field="txtoperator" title="文字结果条件" width="95" sortable>
                        <template v-slot="{ row }">
                            <el-select v-model="row.txtoperator" placeholder="请选择">
                                <el-option v-for="item in operatorOptions" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="txtresults" title="文字结果（多个,隔开）" width="160" :edit-render="{name: 'input',autoselect: true}" sortable></vxe-table-column>
                    <vxe-table-column field="txtlike" sortable title="文字模糊匹配" width="100" align="center">
                        <template v-slot="{ row }">
                            <el-checkbox v-model="row.txtlike" true-label="1" false-label="0"></el-checkbox>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="mustinclude" title="必选条件" width="60" align="center">
                        <template v-slot="{ row }">
                            <el-checkbox v-model="row.mustinclude" true-label="1" false-label="0"></el-checkbox>
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </div>
            <div v-if="condtype == 2" style="height:270px">
                <vxe-table ref="medTable" show-overflow :data.sync="condList" height="auto" resizable stripe border size="mini" 
                    header-align="center" show-header-overflow highlight-current-row @cell-dblclick="cellDblclick" 
                    :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, showIcon: false }">
                    <vxe-table-column field="seq" title="序号" align="center" width="55" :edit-render="{name: 'input'}" sortable></vxe-table-column>
                    <vxe-table-column field="medname" title="抗生素(双击弹窗)" width="200" :edit-render="{name:'input', autoselect: true, attrs: {readonly: true}}" sortable></vxe-table-column>
                    <vxe-table-column field="medresult" title="耐药结果" width="200" sortable>
                        <template v-slot="{ row }">
                            <el-autocomplete :popper-append-to-body="true" v-model="row.medresult" :fetch-suggestions="queryMedresult" @select="medresultChange($event, row)" popper-class="mini-select select-box" style="width:100%;">
                                <template slot-scope="{ item }">
                                    <div class="name" style="width: 200px">{{ item.name }}</div>
                                </template>
                            </el-autocomplete>
                        </template>
                    </vxe-table-column>
                    <!-- <vxe-table-column field="mustinclude" title="必选条件" width="60" align="center">
                        <template v-slot="{ row }">
                            <el-checkbox v-model="row.mustinclude" true-label="1" false-label="0"></el-checkbox>
                        </template>
                    </vxe-table-column> -->
                </vxe-table>
            </div>
            <!-- <div class="detail-operation"> -->
            <!-- <div style="font-size:17px;padding:3px;background-color:#fff;text-align:center;font-weight:bold">
                <el-button icon="el-icon-plus" style="align:left" class="el-button--310" @click="addItem()">新增明细</el-button>
                <el-button icon="el-icon-delete" style="align:left" class="el-button--310" @click="delItem()">删除明细</el-button>
            </div> -->

        </div>
        <el-dialog width="1000px" top="10px" :append-to-body="true" :close-on-click-modal="false" title="选择报告项目" :visible.sync="rptitemDialog" :destroy-on-close="true">
            <rm-pop-rptitem :prgno="prono" :rptunitid="rptunitid" :isAllRpt="1" @cancel="rptitemDialog=false;" @selitem="rptitemChange"></rm-pop-rptitem>
        </el-dialog>
        <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="请选择抗生素" :visible.sync="medDialog" @opened="clearMedqcode">
            <rm-pop-common ref="meddialog" datatype="labmed" @change="medChange" @cancel="medDialog=false;"></rm-pop-common>
        </el-dialog>
        <el-dialog width="1000px" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="耐药机制选择" :visible.sync="dialogMultipleVisible" :destroy-on-close="true">
            <rm-SqlMultiple :leftOption="option1" :rightOption="option2" :name="fieldname" @change="closedialog"></rm-SqlMultiple>
        </el-dialog>
    </div>
</template>

<script>
import XEUtils from "xe-utils"; //引入工具类
export default {
    name: "rm-customcond",
    props: {
        prono: {
            type: String,
            default: "",
            request: true,
        },
        rptunitid: {
            type: Number,
            default: 0,
            request: false,
        },
        condtype: { // 1 为多项目自定义弹窗，2 为药敏自定义弹窗
            type: Number,
            default: 1,
            request: false,
        },
        condData: {
            type: Array,
            default: () => [],
            request: true,
        },
    },
    data() {
        return {
            operatorOptions: [
                {
                    value: "In",
                    label: "等于",
                },
                {
                    value: "NotIn",
                    label: "不等于",
                },
            ],
            addPowerflag: false,
            utype: "",
            labqueryflag: false,
            labqueryParam: {},
            condList: [],
            // tempComData: [],
            selrow: {},
            rptitemDialog: false,
            medDialog: false,
            medresultList: [
                {name: "耐药"},
                {name: "敏感"},
                {name: "中介"},
            ],
            rescodeOption:[],
            dialogMultipleVisible:false,
            option1:"",
            option2:"",
            fieldname:"",
        }
    },
    created() {
        this.initOption();
    },
    mounted() {
        this.getLoginuser();
        this.condList = this.condData;
        this.setcurrent();
    },
    methods: {
        initOption() {
            this.$tool.request({
                url: "ucent/customcond",
                method: "post",
                data: {
                    action: "initoption",
                    prono: this.prono,
                },
            }).then(response => {
                this.addPowerflag = response.paddflag;
                this.rescodeOption = response.rescodeOption;
            })
            .catch(e => { });
        },
        setcurrent(){
            if(this.condList.length >0 ){
                this.$refs.resultTable.setCurrentRow(this.condList[0]);
            }
        },
        getLoginuser() {
            this.utype = this.$tool.getSession(this.$tool.loginutype);
            if (this.utype == "G") {
                this.labqueryParam.createuser = "_Global_";
            } else {
                this.labqueryParam.createuser = this.$tool.getSession(this.$tool.loginusername);
            }
            console.log(this.labqueryParam.createuser)
        },
        nextFocus(index) { //多项目条件回车
            if (index > 2) return false;
            var that = this;
            var focusIndex = index + 1;
            setTimeout(function () {
                that.$refs["input" + focusIndex].focus();
            }, 1);
        },
        btnSure() { //确定
            let condData =[];
            if (this.condtype == 1) {
                condData = XEUtils.clone(this.$refs.resultTable.getTableData().fullData, true);
            } else if (this.condtype == 2) {
                condData = XEUtils.clone(this.$refs.medTable.getTableData().fullData, true);
            }
            this.$emit("refreshLaboption", 2, condData); // 2 为关闭弹窗，更新数据
        },
        btnCancel() { //取消
            this.$emit("refreshLaboption", 3, ""); // 3 为关闭弹窗，不操作数据
        },
        addItem() { //增加明细
            let tablename = "resultTable";
            let addParam = {};
            if (this.condtype == 1) {
                addParam = {
                    queryresultno: this.labqueryParam.queryresultno,
                    seq: this.$refs.resultTable.tableFullData.length > 0 ? (Math.floor(this.$refs.resultTable.tableFullData[this.$refs.resultTable.tableFullData.length - 1].seq / 10) + 1) * 10 : 10,
                    txtoperator: "In",
                    txtlike: 0,
                    mustinclude: "1",
                    resistrules:"",
                };
            } else if (this.condtype == 2) {
                tablename = "medTable";
                addParam = {
                    queryresultno: this.labqueryParam.queryresultno,
                    seq: this.$refs.medTable.tableFullData.length > 0 ? (Math.floor(this.$refs.medTable.tableFullData[this.$refs.medTable.tableFullData.length - 1].seq / 10) + 1) * 10 : 10,
                    // mustinclude: "1", 药敏必选暂时不用
                };
            }
            this.$refs[tablename].insert({...addParam}).then(({ row }) => {
                this.$nextTick(() => {
                    this.$refs[tablename].setCurrentRow(row);
                });
            });
        },
        delItem() { //删除明细
            let tablename = "resultTable";
            if (this.condtype == 2) {
                tablename = "medTable";
            }
            var delrow = this.$refs[tablename].getCurrentRow();
            if (delrow) {
                var alld = this.$refs[tablename].tableData;
                var rowindex = alld.indexOf(delrow);
                this.$refs[tablename].remove(delrow);
                let havedata = this.$refs[tablename].tableData;
                if (havedata.length > 0) {
                    if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                    let selectrow = havedata[rowindex];
                    this.$refs[tablename].setCurrentRow(selectrow);
                } else {
                    this.$refs[tablename].setCurrentRow(null);
                }
            } else {
                this.$message({
                    message: "请先选中要删除的明细！",
                    type: "warning",
                });
            }
        },
        btnToSave() { //前往维护
                this.labqueryflag = true;
                setTimeout(() => {
                    this.$refs.input1.focus();
                }, 30);
        },
        btnGoBack() { //返回
            this.labqueryflag = false;
        },
        saveLabquery() { //保存多项目、药敏条件
            let data = [];
            if (this.condtype == 1) {
                data = this.$refs.resultTable.getTableData().fullData;
            } else if (this.condtype == 2) {
                data = this.$refs.medTable.getTableData().fullData;
            }
            for (let i = 0, len = data.length; i < len; i++) {
                let tempseq = (i + 1) * 10;
                if (tempseq !== data[i].seq) {
                    data[i].seq = tempseq;
                }
                data[i].queryresultno = this.labqueryParam.queryresultno; //修正主键
            }
            this.$tool.request({
                url: "ucent/customcond",
                method: "post",
                data: {
                    action: "savelabquery",
                    prono: this.prono,
                    addparam: this.labqueryParam,
                    upt: data,
                    condtype: this.condtype,
                },
            }).then(response => {
                if (response.flag == "1") {
                    this.$message.success("保存组合成功！");
                    // 此处关闭弹窗，需要返回当前设置的自定义值；若不关闭弹窗，可在点击确定之后返回
                    // this.bResultCombDlg = false; // 关闭弹窗，暂时不返回值，通过下拉框进行选择已经添加的值
                    this.$emit("refreshLaboption", 1, ""); // 1 为关闭弹窗并刷新下拉框数据
                    this.labqueryflag = false;
                } else {
                    this.$message.error(res.errmsg);
                }
            }).catch(e => { });
        },
        cellDblclick({ row, column }) { // 报告项目、药敏弹窗
            this.selrow = row;
            if (this.condtype == 1) {
                if (column.property == "rpt_itemname") {
                    this.rptitemDialog = true;
                }
            } else if (this.condtype == 2) {
                if (column.property == "medname") {
                    this.medDialog = true;
                }
            }
        },
        rptitemChange(code, name) {
            this.selrow.rpt_itemcode = code;
            this.selrow.rpt_itemname = name;
            this.rptitemDialog = false;
        },
        clearMedqcode() {
            console.log(this.$refs.meddialog);
            // console.log(this.$refs.medpop.$refs)
            // console.log(this.$refs.medpop.$refs.qcodeinput)
            this.$refs.meddialog.qcode = "";
        },
        medChange(code, name) {
            this.selrow.medcode = code;
            this.selrow.medname = name;
            this.medDialog = false;
        },
        queryMedresult(str, cb) {
            cb(this.medresultList);
        },
        medresultChange(e, row) {
            row.medresult = e.name;
        },
        popMultipleChk(e, fieldname, option, title) {
            let temp = XEUtils.clone(option, true)
            this.option1 = []
            this.option2 = []
            if (e != "") {
                let k = e.split(",")
                k.forEach((item) => {
                    let ndata = temp.find((m) => m.data == item)
                    if (ndata != undefined && ndata != null) {
                        this.option2.push(ndata)
                    }
                })
                temp.forEach((item) => {
                    if (k.indexOf(item.data + "") < 0) {
                        this.option1.push(item)
                    }
                })
            } else {
                this.option1 = temp
            }
            this.fieldname = fieldname
            this.dialogMultipleVisible = true
        },
        closedialog(value, name) {
            console.log(value,"value");
            if (value != "close") {
                let row = this.$refs.resultTable.getCurrentRow();
                if(row){
                    row.resistrules=value;
                }
            }
            this.dialogMultipleVisible = false
        },
    }
}
</script>

<style lang="scss" scoped>
.customcond-content {
    color: #000000;
    font-size: 12px;
    .param-row {
        display: flex;
        .param-title {
            width: 75px;
            margin: 0 5px 0 0;
            text-align: right;
            line-height: 26px;
        }
        .param-text {
            width: 180px;
        }
    }
    .customcond-operate {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
        .medcond-tip {
            color: blue;
            line-height: 24px;
        }
    }
}
</style>